package app.softtech.freechat.app;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

import android.app.Application;
import android.text.TextUtils;
import app.softtech.freechat.utils.LruBitmapCache;

public class AppController extends Application {
	private static final String TAG = AppController.class.getSimpleName();
	
	private RequestQueue mRequestQueue;
	
	//Attributes used to load image from URL
	private ImageLoader mImageLoader;
	
	//Attributes used to retrieve an instance of the class
	private static AppController mInstance;

	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
	}
	
	/**
	 * Function used to retrieve an instance of the class
	 * @return an instance of the class
	 */
	public static synchronized AppController getInstance(){
		return mInstance;
	}
	
	/**
	 * Function used to get request queue
	 * @return
	 */
	public RequestQueue getRequestQueue(){
		if(mRequestQueue == null){
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}
		return mRequestQueue;
	}
	
	/**
	 * Function used to get image loader 
	 * @return
	 */
	public ImageLoader getImageLoader(){
		getRequestQueue();
		if(mImageLoader == null){
			mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
		}
		return mImageLoader;
	}
	
	/**
	 * 
	 * @param request
	 * @param tag
	 */
	public <T> void addToRequestQueue(Request<T> request, String tag){
		request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
		getRequestQueue().add(request);
	}
	
	/**
	 * 
	 * @param request
	 */
	public <T> void addToRequestQueue(Request <T> request){
		request.setTag(TAG);
		getRequestQueue().add(request);
	}
	
	/**
	 * 
	 * @param tag
	 */
	public void cancelPendingRequests(Object tag){
		if(mRequestQueue != null){
			getRequestQueue().cancelAll(tag);
		}
	}
}
